from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import reader,publisher,book
from .Xlh import ReaderSerializer,BookSerializer,PublisherSerializer
from django.core.paginator import Paginator
# Create your views here.

class shujiadd(APIView):
    def post(self,request):
        name=request.data.get('name')
        publisher_id=request.data.get('publisher_id')
        status01=request.data.get('status')
        reader=request.data.get('reader')

        if not all([name,publisher_id,status01]):
            return Response({
                'message':'不能为空'
            })


        if publisher.objects.filter(id=publisher_id).exists():
            book01=book.objects.create(name=name,reader=reader,publisher_id=publisher_id,status=status01)
            book01.save()
            serializer01=BookSerializer(book01)
            return Response({
                'message':'添加成功',
                'data':serializer01.data,
            })
        else:
            return Response({
                'message':'已存在'
            })


class chazhao_01(APIView):
    def get(self,request,id):
        quanban=publisher.objects.get(id=id)
        serializer=PublisherSerializer(quanban)
        return Response({
            'message':'查找成功',
            'data':serializer.data
        })

class chazhao_02(APIView):
    def get(self,request,id):
        quanban=book.objects.get(id=id)
        serializer=BookSerializer(quanban)
        return Response({
            'message':'查找成功',
            'data':serializer.data
        })

class Fenye(APIView):

    def get(self,request):
        quanban=publisher.objects.all()

        page=request.GET.get('page',1)
        per_page=request.GET.get('per_page',2)

        id=request.GET.get('id')
        if id:
            quanban=quanban.filter(id=id)

        paginator = Paginator(quanban,per_page)
        current_page=paginator.page(page)
        serializer=PublisherSerializer(current_page,many=True)

        return Response({

            'data':serializer.data,
            'tatal':paginator.count,
            'zongshu':paginator.count,
            'page':page,
            'per_page':per_page,

        })




